
package de.swta.freezay.components;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.time.Duration;

/**
 * A CountDownLabel displays a date and count down this date till current date
 *
 * @author Christian Baeumer
 */
public class CountDownLabel extends MultiLineLabel {

    /** Updateing behaviour for this component */
    private final AjaxSelfUpdatingTimerBehavior updatingBehaviour;

    /* Date formatter for the reamining date/time */
    private final SimpleDateFormat remainingDateFormatter;
    /* Date formatter for the absolute date/time */
    private final SimpleDateFormat dateFormatter;
    /* remaining date */
    private final Date remaining;
    /* the text of the label */
    private String labelText;

    /**
     * Constructor
     *
     * @param id the markupID
     * @param validity the date to count down
     */
    public CountDownLabel(final String id, final Date validity) {
        super(id);

        /* set up the updating behaviour of this component to rerender
         * every second */
        updatingBehaviour = new AjaxSelfUpdatingTimerBehavior(
                Duration.ONE_SECOND);
        add(updatingBehaviour);

        /* set up the remainingDateFormatter */
        remainingDateFormatter = new SimpleDateFormat("DD 'Tage' HH:mm:ss");
        remainingDateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));

        /* set up the absoluteDateFormatter */
        dateFormatter = new SimpleDateFormat();

        /* now :) */
        remaining = new Date();

        /* set up the model of this component */
        setDefaultModel(new Model<String>() {

            @Override
            public String getObject() {
                /* get now in millis */
                long currentTime = System.currentTimeMillis();
                /* get count down date in millis */
                long validityTime = validity.getTime();

                /* check validity */
                if (validityTime > currentTime) {
                    remaining.setTime(validityTime - currentTime);
                    labelText = remainingDateFormatter.format(remaining);
                    labelText +="\n(" + dateFormatter.format(validityTime)
                            + ")";
                } else {
                    labelText = "expired";
                    /* if date is expired the component can stop rendering
                     * itself every second */
                    CountDownLabel.this.updatingBehaviour.stop();
                }
                
                return labelText;
            }
        });
    }

}
